from common.models.check_report import CheckReport
from flask import Blueprint, request, make_response, redirect
import json, requests
from application import app, db
import datetime
from common.libs.Helper import dingtalkpost, dicgetkey
from config.dingtalk_setting import column, vacationdic
from common.models.user import User
from common.models.department import Department
from common.libs.DataHelper import getCurrentTime, getCurrentDate
from sqlalchemy import and_, or_, func
from application import db
import urllib.parse
from config.dingtalk_setting import AppKey, AppSecret, AgentId, role_hr, bpmid
from dingtalk import SecretClient, model

check_page = Blueprint("check_page", __name__)

client = SecretClient(AppKey, AppSecret)  # 新 access_token 获取方式


# @check_page.route("/add", methods=['GET', 'POST'])
# def add():
#     res = request.values.to_dict()
#     userid = res['userid']
#     type = res['type']
#     time = res['time'][0:10]
#
#     savetime = datetime.datetime.fromtimestamp(int(time))
#
#     check = CheckOrdata()
#     check.userid = userid
#     check.time = savetime
#     check.type = type
#     db.session.add(check)
#     db.session.commit()
#     return json.dumps("info", ensure_ascii=False)


@check_page.route("/syncheck", methods=['GET', 'POST'])
def syncheck():
    depid = request.json.get('depid')
    stime = request.json.get('stime')
    etime = request.json.get('etime')

    # stime = "2022-11-01 12:12:12"
    # etime = "2022-12-01 12:12:12"

    user = User.query.filter(User.depid == depid).filter(
        or_(User.status == 4, User.status == 1)).all()
    for item in user:
        otherconstent = {
            "column_id_list": column["sattend"] + "," + column["attend"] + "," + column[
                "absent"] + "," + "," + column["late"] + "," + column[
                                  "leave"] + "," + column[
                                  "replace"] + "," + column["lackoff"] + "," + column[
                                  "lackon"] + "," + column["ot"] + "," + column[
                                  "otrd"] + "," + column["otwd"] + "," + column["othd"] + "," + column["otrdc"] + "," +
                              column["otwdc"] + "," + column["othdc"] + "," + column["bedlate"] + "," + column[
                                  "otrdcf"] + "," +
                              column["otwdcf"] + "," + column["othdcf"],
            "from_date": stime,
            "to_date": etime,
            "userid": item.userid
        }

        vacationconstent = {
            "from_date": stime,
            "to_date": etime,
            "leave_names": "事假,年假,婚假,病假,产假,陪产假,婚假,丧假,加班调休,出差调休",
            "userid": item.userid
        }
        print(otherconstent)

        otherurl = 'https://oapi.dingtalk.com/topapi/attendance/getcolumnval'
        vacationurl = 'https://oapi.dingtalk.com/topapi/attendance/getleavetimebynames'
        other = dingtalkpost(otherurl, otherconstent)
        vacation = dingtalkpost(vacationurl, vacationconstent)

        # 考勤查询日期循环
        print(other)
        for i in range(len(other['result']['column_vals'][0]['column_vals'])):
            checkdic = {}
            # 具体数据列循环
            for item2 in range(len(other['result']['column_vals'])):
                colid = dicgetkey(str(other['result']['column_vals'][int(item2)]['column_vo']['id']), column)
                colvalue = other['result']['column_vals'][int(item2)]['column_vals'][int(i)]['value']
                coldate = other['result']['column_vals'][int(item2)]['column_vals'][int(i)]['date']
                checkid = str(item.id) + coldate[0:10].replace('-', '')
                checkdic.update({"id": int(checkid)})
                checkdic.update({"date": coldate})
                checkdic.update({colid: colvalue})
            for item2 in range(len(vacation['result']['columns'])):
                colid = vacationdic[vacation['result']['columns'][int(item2)]['columnvo']['name']]
                colvalue = vacation['result']['columns'][int(item2)]['columnvals'][int(i)]['value']
                checkdic.update({colid: colvalue})
            check = CheckReport.query.filter_by(id=checkdic["id"]).first()

            if check:
                check.late = checkdic["late"]
                check.leave = checkdic["leave"]
                check.leave = checkdic["leave"]
                check.absent = checkdic["absent"]
                check.person = checkdic["person"]
                check.sick = checkdic["sick"]
                check.mate = checkdic["mate"]
                check.ot = checkdic["ot"]
                check.sattend = checkdic["sattend"]
                check.attend = checkdic["attend"]
                check.otwd = checkdic["otwd"]
                check.otrd = checkdic["otrd"]
                check.othd = checkdic["othd"]
                check.otwdc = checkdic["otwdc"]
                check.otrdc = checkdic["otrdc"]
                check.othdc = checkdic["othdc"]
                check.replace = checkdic["replace"]
                check.lackon = checkdic["lackon"]
                check.lackoff = checkdic["lackoff"]
                check.bedlate = checkdic["bedlate"]
                check.otwdcf = checkdic["otwdcf"]
                check.otrdcf = checkdic["otrdcf"]
                check.othdcf = checkdic["othdcf"]
                check.pregnant = checkdic["pregnant"]
                check.dead = checkdic["dead"]
                check.annual = checkdic["annual"]
                check.otexchange = checkdic["otexchange"]
                check.btexchange = checkdic["btexchange"]
                check.withpregnant = checkdic["withpregnant"]

                check.updated_time = getCurrentTime()
                db.session.commit()
            else:
                newcheck = CheckReport()

                newcheck.id = checkdic["id"]
                newcheck.date = checkdic["date"]
                newcheck.userid = item.id

                newcheck.late = checkdic["late"]
                newcheck.leave = checkdic["leave"]
                newcheck.leave = checkdic["leave"]
                newcheck.absent = checkdic["absent"]
                newcheck.person = checkdic["person"]
                newcheck.sick = checkdic["sick"]
                newcheck.mate = checkdic["mate"]
                newcheck.ot = checkdic["ot"]
                newcheck.sattend = checkdic["sattend"]
                newcheck.attend = checkdic["attend"]
                newcheck.otwd = checkdic["otwd"]
                newcheck.otrd = checkdic["otrd"]
                newcheck.othd = checkdic["othd"]
                newcheck.otwdc = checkdic["otwdc"]
                newcheck.otrdc = checkdic["otrdc"]
                newcheck.othdc = checkdic["othdc"]
                newcheck.replace = checkdic["replace"]
                newcheck.lackon = checkdic["lackon"]
                newcheck.lackoff = checkdic["lackoff"]
                newcheck.bedlate = checkdic["bedlate"]
                newcheck.otwdcf = checkdic["otwdcf"]
                newcheck.otrdcf = checkdic["otrdcf"]
                newcheck.othdcf = checkdic["othdcf"]
                newcheck.pregnant = checkdic["pregnant"]
                newcheck.dead = checkdic["dead"]
                newcheck.annual = checkdic["annual"]
                newcheck.otexchange = checkdic["otexchange"]
                newcheck.btexchange = checkdic["btexchange"]
                newcheck.withpregnant = checkdic["withpregnant"]

                newcheck.created_time = getCurrentTime()

                db.session.add(newcheck)
                db.session.commit()

                #     newcheck.item4=checkdic[item4]
                # db.session.add(newcheck)
                # db.session.commit()

        # late = sum(int(item["value"]) for item in other['result']['column_vals'][0]['column_vals'])
        # leave = sum(int(item["value"]) for item in other['result']['column_vals'][1]['column_vals'])
        # absent = sum(int(item["value"]) for item in other['result']['column_vals'][2]['column_vals'])
        # overtime = sum(float(item["value"]) for item in other['result']['column_vals'][3]['column_vals'])
        #
        # person = sum(float(item["value"]) for item in vacation['result']['columns'][0]['columnvals'])
        # sick = sum(float(item["value"]) for item in vacation['result']['columns'][1]['columnvals'])
        # mate = sum(float(item["value"]) for item in vacation['result']['columns'][2]['columnvals'])
        # pate = sum(float(item["value"]) for item in vacation['result']['columns'][3]['columnvals'])
        #
        # report = CheckReport()
        # report.name = item.name
        # report.userid = item.userid
        # report.department = item.department.name
        # report.late = late
        # report.leave = leave
        # report.absent = absent
        # report.overtime = overtime
        # report.person = person
        # report.sick = sick
        # report.mate = mate
        # report.pate = pate
        # report.status = 0
        # db.session.add(report)
        # db.session.commit()
    dep = Department.query.filter_by(id=depid).first()
    depname = dep.name
    return json.dumps(depname, ensure_ascii=False)


# @check_page.route("/test", methods=['GET', 'POST'])
# def test():
#     time.sleep(3)
#     return json.dumps("info", ensure_ascii=False)


@check_page.route("/showcheckreport", methods=['GET', 'POST'])
def showcheckreport():
    selecarr = request.json.get('selecarr')
    stime = request.json.get('stime')
    etime = request.json.get('etime')

    check_report = db.session.query(CheckReport.id, CheckReport.userid, User.name,
                                    func.sum(CheckReport.late).label("sumlate"),
                                    func.sum(CheckReport.leave).label("sumleave"),
                                    func.sum(CheckReport.absent).label("sumabsent"),
                                    func.sum(CheckReport.person).label("sumperson"),
                                    func.sum(CheckReport.sick).label("sumsick"),
                                    func.sum(CheckReport.mate).label("summate"),
                                    func.sum(CheckReport.ot).label("sumot"),
                                    func.sum(CheckReport.sattend).label("sumsattend"),
                                    func.sum(CheckReport.attend).label("sumattend"),
                                    func.sum(CheckReport.otwd).label("sumotwd"),
                                    func.sum(CheckReport.otrd).label("sumotrd"),
                                    func.sum(CheckReport.othd).label("sumothd"),
                                    func.sum(CheckReport.otwdc).label("sumotwdc"),
                                    func.sum(CheckReport.otrdc).label("sumotrdc"),
                                    func.sum(CheckReport.othdc).label("sumothdc"),
                                    func.sum(CheckReport.replace).label("sumreplace"),
                                    func.sum(CheckReport.lackon).label("sumlackon"),
                                    func.sum(CheckReport.lackoff).label("sumlackoff"),
                                    func.sum(CheckReport.bedlate).label("sumbedlate"),
                                    func.sum(CheckReport.otwdcf).label("sumotwdcf"),
                                    func.sum(CheckReport.otrdcf).label("sumotrdcf"),
                                    func.sum(CheckReport.othdcf).label("sumothdcf"),
                                    func.sum(CheckReport.pregnant).label("sumpregnant"),
                                    func.sum(CheckReport.dead).label("sumdead"),
                                    func.sum(CheckReport.annual).label("sumannual"),
                                    func.sum(CheckReport.otexchange).label("sumotexchange"),
                                    func.sum(CheckReport.btexchange).label("sumbtexchange"),
                                    func.sum(CheckReport.withpregnant).label("sumwithpregnant")).join(User,
                                                                                                      User.id == CheckReport.userid).filter(
        CheckReport.date >= stime, CheckReport.date <= etime).filter(User.depid.in_(selecarr)).group_by(
        CheckReport.userid).all()
    rts = []
    for item in check_report:
        temp = dict(name=item.name, userid=item.userid, late=round(item.sumlate, 2), leave=round(item.sumleave, 2),
                    absent=round(item.sumabsent, 2), person=round(item.sumperson, 2), sick=round(item.sumsick, 2),
                    mate=round(item.summate, 2),
                    ot=round(item.sumot, 2),
                    sattend=round(item.sumsattend, 2), attend=round(item.sumattend, 2), otwd=round(item.sumotwd, 2),
                    otrd=round(item.sumotrd, 2),
                    othd=round(item.sumothd, 2), otwdc=round(item.sumotwdc, 2), otrdc=round(item.sumotrdc, 2),
                    othdc=round(item.sumothdc, 2),
                    replace=round(item.sumreplace, 2), lackon=round(item.sumlackon, 2),
                    lackoff=round(item.sumlackoff, 2),
                    bedlate=round(item.sumbedlate, 2), otwdcf=round(item.sumotwdcf, 2), otrdcf=round(item.sumotrdcf, 2),
                    othdcf=round(item.sumothdcf, 2), pregnant=item.sumpregnant, dead=round(item.sumdead, 2),
                    annual=round(item.sumannual, 2), otexchange=round(item.sumotexchange, 2),
                    btexchange=round(item.sumbtexchange, 2),
                    withpregnant=round(item.sumwithpregnant, 2))
        rts.append(temp)
    return json.dumps(rts, ensure_ascii=False)


@check_page.route("/showcheckdetail", methods=['GET', 'POST'])
def showcheckdetail():
    userid = request.json.get('userid')
    stime = request.json.get('stime')
    etime = request.json.get('etime')

    user = User.query.filter(User.id == userid).first()
    username = user.name
    userdep = user.department.name

    check_report = CheckReport.query.filter(CheckReport.date >= stime, CheckReport.date <= etime,
                                            CheckReport.userid == userid).all()
    rts = []
    for item in check_report:
        temp = dict(userid=item.userid, date=str(item.date), late=item.late, leave=item.leave,
                    absent=item.absent, person=item.person, sick=item.sick,
                    mate=item.mate,
                    ot=item.ot,
                    sattend=item.sattend, attend=item.attend, otwd=item.otwd,
                    otrd=item.otrd,
                    othd=item.othd, otwdc=item.otwdc, otrdc=item.otrdc,
                    othdc=item.othdc,
                    replace=item.replace, lackon=item.lackon,
                    lackoff=item.lackoff,
                    bedlate=item.bedlate, otwdcf=item.otwdcf, otrdcf=item.otrdcf,
                    othdcf=item.othdcf, pregnant=item.pregnant, dead=item.dead,
                    annual=item.annual, otexchange=item.otexchange,
                    btexchange=item.btexchange,
                    withpregnant=item.withpregnant)
        rts.append(temp)
    return json.dumps({"table": rts, "username": username, "userdep": userdep}, ensure_ascii=False)


@check_page.route("/sendannual", methods=['GET', 'POST'])
def sendannual():
    content = {
        "op_userid": "056411420820728054",
        "leave_quotas": [
            {
                "start_time": 1641030274000,
                "reason": "管理员导入",
                "quota_num_per_day": 500,
                "quota_cycle": "2022",
                "end_time": 1672479874000,
                "leave_code": "694e75be-c4bc-4547-ab54-796175eba2b0",
                "userid": "056411420820728054"
            }
        ],
    }

    url = "https://oapi.dingtalk.com/topapi/attendance/vacation/quota/init"
    a = dingtalkpost(url=url, content=content)

    return json.dumps(a, ensure_ascii=False)


@check_page.route("/addannual", methods=['GET', 'POST'])
def addannual():
    content = {
        "when_can_leave": "entry",
        "leave_time_ceil_min_unit": "hour",
        "visibility_rules": {
            "visible": "056411420820728054",
            "type": "staff"
        },
        "leave_view_unit": "day",
        "leave_name": "员工年假",
        "biz_type": "general_leave",
        "min_leave_hour": "2",
        "extras": "{\"validity_type\":\"absolute_time\",\"validity_value\":\"12-31\"}",
        "freedom_leave": "false",
        "submit_time_rule": {
            "enable_time_limit": "false",
            "time_type": "before",
            "time_value": "1",
            "time_unit": "day"
        },
        "op_userid": "056411420820728054",
        "natural_day_leave": "true",
        "paid_leave": "true",
        "leave_time_ceil": "false",
        "hours_in_per_day": "1000",
        "leave_hour_ceil": "up",
        "leave_certificate": {
            "duration": "1",
            "unit": "hour",
            "enable": "false",
            "prompt_information": "请假信息"
        },
        "max_leave_time": "1"
    }

    url = "https://oapi.dingtalk.com/topapi/attendance/vacation/type/create"
    a = dingtalkpost(url=url, content=content)

    return json.dumps(a, ensure_ascii=False)


@check_page.route("/updataannual", methods=['GET', 'POST'])
def updataannual():
    content = {
        "natural_day_leave": False,
        "leave_view_unit": "day",
        "hours_in_per_day": 800,
        "leave_name": "员工年假",
        "biz_type": "general_leave",
        "extras": "{\"validity_type\":\"absolute_time\",\"validity_value\":\"12-31\"}",
        "leave_code": "694e75be-c4bc-4547-ab54-796175eba2b0",
        "op_userid": "056411420820728054",
        "leave_certificate": {
            "unit": "hour",
            "duration": 1,
            "enable": False,
            "prompt_information": "请假信息"
        },
        "submit_time_rule": {
            "time_value": 18,
            "time_unit": "day",
            "time_type": "before",
            "enable_time_limit": False
        }
    }

    url = "https://oapi.dingtalk.com/topapi/attendance/vacation/type/update"
    a = dingtalkpost(url=url, content=content)

    return json.dumps(a, ensure_ascii=False)


@check_page.route("/getcheckreport", methods=['GET', 'POST'])
def getcheckreport():
    userid = request.json.get('userid')
    stime = request.json.get('stime')
    etime = request.json.get('etime')

    check_report = db.session.query(CheckReport.id, CheckReport.userid, User.name,
                                    func.sum(CheckReport.late).label("sumlate"),
                                    func.sum(CheckReport.leave).label("sumleave"),
                                    func.sum(CheckReport.absent).label("sumabsent"),
                                    func.sum(CheckReport.person).label("sumperson"),
                                    func.sum(CheckReport.sick).label("sumsick"),
                                    func.sum(CheckReport.mate).label("summate"),
                                    func.sum(CheckReport.otwdc).label("sumotwdc"),
                                    func.sum(CheckReport.otrdc).label("sumotrdc"),
                                    func.sum(CheckReport.othdc).label("sumothdc"),
                                    func.sum(CheckReport.lackon).label("sumlackon"),
                                    func.sum(CheckReport.lackoff).label("sumlackoff"),
                                    func.sum(CheckReport.bedlate).label("sumbedlate"),
                                    func.sum(CheckReport.otwdcf).label("sumotwdcf"),
                                    func.sum(CheckReport.otrdcf).label("sumotrdcf"),
                                    func.sum(CheckReport.othdcf).label("sumothdcf"),
                                    func.sum(CheckReport.pregnant).label("sumpregnant"),
                                    func.sum(CheckReport.dead).label("sumdead"),
                                    func.sum(CheckReport.annual).label("sumannual"),
                                    func.sum(CheckReport.otexchange).label("sumotexchange"),
                                    func.sum(CheckReport.btexchange).label("sumbtexchange"),
                                    func.sum(CheckReport.withpregnant).label("sumwithpregnant")).join(User,
                                                                                                      User.id == CheckReport.userid).filter(
        CheckReport.date >= stime, CheckReport.date <= etime).filter(User.id == userid).group_by(
        CheckReport.userid).all()
    rts = []
    for item in check_report:
        temp = dict(name=item.name, userid=item.userid, late=round(item.sumlate, 2), leave=round(item.sumleave, 2),
                    absent=round(item.sumabsent, 2), person=round(item.sumperson / 8, 2),
                    sick=round(item.sumsick / 8, 2),
                    mate=round(item.summate, 2),
                    otc=round(item.sumotwdc + item.sumotrdc + item.sumothdc, 2),
                    lack=round(item.sumlackon + item.sumlackoff, 2),
                    bedlate=round(item.sumbedlate, 2),
                    otf=round(item.sumotwdcf + item.sumotrdcf + item.sumothdcf, 2), pregnant=item.sumpregnant,
                    dead=round(item.sumdead, 2),
                    annual=round(item.sumannual, 2), otexchange=round(item.sumotexchange, 2),
                    btexchange=round(item.sumbtexchange, 2),
                    withpregnant=round(item.sumwithpregnant, 2))
        rts.append(temp)
    return json.dumps(rts, ensure_ascii=False)


@check_page.route('/sendconfirmbydep', methods=['GET', 'POST'])
def sendconfirmbydep():
    selecarr = request.json.get('selecarr')
    stime = request.json.get('stime')
    etime = request.json.get('etime')

    renyuan = User.query.filter(User.depid.in_(selecarr)).filter(
        or_(User.status == 4, User.status == 1)).all()

    # renyuan = User.query.filter(
    #     or_(User.status == 4, User.status == 1)).filter(User.id >= 49999).all()

    userlist = []
    for i in renyuan:
        userlist.append(i.userid)

    for i in userlist:
        user = User.query.filter_by(userid=i).first()
        id = str(user.id)
        name = user.name

        base_url = 'http://101.132.227.54:88/checkconfirm?userid=' + id + '&stime=' + stime[0:10] + '&etime=' + etime[
                                                                                                                0:10]
        encodeurl = urllib.parse.quote(base_url)

        dingtalkurl = "dingtalk://dingtalkclient/action/openapp?corpid=ding5b2aa85601c5363fffe93478753d9884&container_type=work_platform&app_id=0_1784691312&redirect_type=jump&redirect_url=" + encodeurl
        normalurl = "dingtalk://dingtalkclient/page/link?url=" + encodeurl + "&pc_slide=true"

        msg = {
            "msgtype": "action_card",
            "action_card": {
                "title": "考勤信息确认",
                "markdown": "![](http://upload.guanzhuoran.cn/confirm.png)   \n   #### 工号:" + id + "   姓名:" + name + " \n   范围:" + stime[
                                                                                                                                   0:10] + "至" + etime[
                                                                                                                                                 0:10],
                "btn_orientation": "1",
                "btn_json_list": [
                    # {
                    #     "title": "完善信息(PC)",
                    #     "action_url": dingtalkurl,
                    # },
                    {
                        "title": "查看详情",
                        "action_url": normalurl,
                    },

                ]
            }
        }

        a = client.message.asyncsend_v2(msg_body=msg, agent_id=AgentId, userid_list=i.split())

    return json.dumps("推送成功", indent=4, sort_keys=True,
                      default=str,
                      ensure_ascii=False)


@check_page.route('/sendconfirmbyuser', methods=['GET', 'POST'])
def sendconfirmbyuser():
    userid = request.json.get('userid')
    stime = request.json.get('stime')
    etime = request.json.get('etime')

    user = User.query.filter_by(id=userid).first()
    id = str(user.id)
    dingtalkuserid = user.userid
    name = user.name

    base_url = 'http://101.132.227.54:88/checkconfirm?userid=' + id + '&stime=' + stime[0:10] + '&etime=' + etime[0:10]
    encodeurl = urllib.parse.quote(base_url)

    dingtalkurl = "dingtalk://dingtalkclient/action/openapp?corpid=ding5b2aa85601c5363fffe93478753d9884&container_type=work_platform&app_id=0_1784691312&redirect_type=jump&redirect_url=" + encodeurl
    normalurl = "dingtalk://dingtalkclient/page/link?url=" + encodeurl + "&pc_slide=true"

    msg = {
        "msgtype": "action_card",
        "action_card": {
            "title": "考勤信息确认",
            "markdown": "![](http://upload.guanzhuoran.cn/confirm.png)   \n   #### 工号:" + id + "   姓名:" + name + " \n   范围:" + stime[
                                                                                                                               0:10] + "至" + etime[
                                                                                                                                             0:10],
            "btn_orientation": "1",
            "btn_json_list": [
                # {
                #     "title": "完善信息(PC)",
                #     "action_url": dingtalkurl,
                # },
                {
                    "title": "查看详情",
                    "action_url": normalurl,
                },

            ]
        }
    }

    a = client.message.asyncsend_v2(msg_body=msg, agent_id=AgentId, userid_list=dingtalkuserid.split("。"))

    return json.dumps("推送成功", indent=4, sort_keys=True,
                      default=str,
                      ensure_ascii=False)


@check_page.route('/autosyncheck', methods=['GET', 'POST'])
def autosyncheck():
    today = datetime.date.today()
    first = today.replace(day=1)
    last_month = first - datetime.timedelta(days=1)
    this_month = today - datetime.timedelta(days=1)
    etime = this_month.strftime("%Y-%m") + "-25"
    stime = last_month.strftime("%Y-%m") + "-26"
    # 同步
    department = Department.query.all()
    for i in department:
        user = User.query.filter(User.depid == i.id).filter(
            or_(User.status == 4, User.status == 1)).all()
        if user:
            for item in user:
                otherconstent = {
                    "column_id_list": column["sattend"] + "," + column["attend"] + "," + column[
                        "absent"] + "," + "," + column["late"] + "," + column[
                                          "leave"] + "," + column[
                                          "replace"] + "," + column["lackoff"] + "," + column[
                                          "lackon"] + "," + column["ot"] + "," + column[
                                          "otrd"] + "," + column["otwd"] + "," + column["othd"] + "," + column[
                                          "otrdc"] + "," +
                                      column["otwdc"] + "," + column["othdc"] + "," + column["bedlate"] + "," + column[
                                          "otrdcf"] + "," +
                                      column["otwdcf"] + "," + column["othdcf"],
                    "from_date": stime,
                    "to_date": etime,
                    "userid": item.userid
                }

                vacationconstent = {
                    "from_date": stime,
                    "to_date": etime,
                    "leave_names": "事假,年假,婚假,病假,产假,陪产假,婚假,丧假,加班调休,出差调休",
                    "userid": item.userid
                }

                otherurl = 'https://oapi.dingtalk.com/topapi/attendance/getcolumnval'
                vacationurl = 'https://oapi.dingtalk.com/topapi/attendance/getleavetimebynames'
                other = dingtalkpost(otherurl, otherconstent)
                vacation = dingtalkpost(vacationurl, vacationconstent)

                # 考勤查询日期循环

                print(vacationconstent)
                print(otherconstent)

                for i in range(len(other['result']['column_vals'][0]['column_vals'])):
                    checkdic = {}
                    # 具体数据列循环
                    for item2 in range(len(other['result']['column_vals'])):
                        colid = dicgetkey(str(other['result']['column_vals'][int(item2)]['column_vo']['id']), column)
                        colvalue = other['result']['column_vals'][int(item2)]['column_vals'][int(i)]['value']
                        coldate = other['result']['column_vals'][int(item2)]['column_vals'][int(i)]['date']
                        checkid = str(item.id) + coldate[0:10].replace('-', '')
                        checkdic.update({"id": int(checkid)})
                        checkdic.update({"date": coldate})
                        checkdic.update({colid: colvalue})
                    for item2 in range(len(vacation['result']['columns'])):
                        colid = vacationdic[vacation['result']['columns'][int(item2)]['columnvo']['name']]
                        colvalue = vacation['result']['columns'][int(item2)]['columnvals'][int(i)]['value']
                        checkdic.update({colid: colvalue})
                    check = CheckReport.query.filter_by(id=checkdic["id"]).first()

                    if check:
                        check.late = checkdic["late"]
                        check.leave = checkdic["leave"]
                        check.leave = checkdic["leave"]
                        check.absent = checkdic["absent"]
                        check.person = checkdic["person"]
                        check.sick = checkdic["sick"]
                        check.mate = checkdic["mate"]
                        check.ot = checkdic["ot"]
                        check.sattend = checkdic["sattend"]
                        check.attend = checkdic["attend"]
                        check.otwd = checkdic["otwd"]
                        check.otrd = checkdic["otrd"]
                        check.othd = checkdic["othd"]
                        check.otwdc = checkdic["otwdc"]
                        check.otrdc = checkdic["otrdc"]
                        check.othdc = checkdic["othdc"]
                        check.replace = checkdic["replace"]
                        check.lackon = checkdic["lackon"]
                        check.lackoff = checkdic["lackoff"]
                        check.bedlate = checkdic["bedlate"]
                        check.otwdcf = checkdic["otwdcf"]
                        check.otrdcf = checkdic["otrdcf"]
                        check.othdcf = checkdic["othdcf"]
                        check.pregnant = checkdic["pregnant"]
                        check.dead = checkdic["dead"]
                        check.annual = checkdic["annual"]
                        check.otexchange = checkdic["otexchange"]
                        check.btexchange = checkdic["btexchange"]
                        check.withpregnant = checkdic["withpregnant"]

                        check.updated_time = getCurrentTime()
                        db.session.commit()
                    else:
                        newcheck = CheckReport()

                        newcheck.id = checkdic["id"]
                        newcheck.date = checkdic["date"]
                        newcheck.userid = item.id

                        newcheck.late = checkdic["late"]
                        newcheck.leave = checkdic["leave"]
                        newcheck.leave = checkdic["leave"]
                        newcheck.absent = checkdic["absent"]
                        newcheck.person = checkdic["person"]
                        newcheck.sick = checkdic["sick"]
                        newcheck.mate = checkdic["mate"]
                        newcheck.ot = checkdic["ot"]
                        newcheck.sattend = checkdic["sattend"]
                        newcheck.attend = checkdic["attend"]
                        newcheck.otwd = checkdic["otwd"]
                        newcheck.otrd = checkdic["otrd"]
                        newcheck.othd = checkdic["othd"]
                        newcheck.otwdc = checkdic["otwdc"]
                        newcheck.otrdc = checkdic["otrdc"]
                        newcheck.othdc = checkdic["othdc"]
                        newcheck.replace = checkdic["replace"]
                        newcheck.lackon = checkdic["lackon"]
                        newcheck.lackoff = checkdic["lackoff"]
                        newcheck.bedlate = checkdic["bedlate"]
                        newcheck.otwdcf = checkdic["otwdcf"]
                        newcheck.otrdcf = checkdic["otrdcf"]
                        newcheck.othdcf = checkdic["othdcf"]
                        newcheck.pregnant = checkdic["pregnant"]
                        newcheck.dead = checkdic["dead"]
                        newcheck.annual = checkdic["annual"]
                        newcheck.otexchange = checkdic["otexchange"]
                        newcheck.btexchange = checkdic["btexchange"]
                        newcheck.withpregnant = checkdic["withpregnant"]

                        newcheck.created_time = getCurrentTime()

                        db.session.add(newcheck)
                        db.session.commit()

    # 成功推送
    userid = "739"

    user = User.query.filter_by(id=userid).first()
    id = str(user.id)
    dingtalkuserid = user.userid
    name = user.name

    base_url = 'http://101.132.227.54:88/checkconfirm?userid=' + id + '&stime=' + stime[0:10] + '&etime=' + etime[0:10]
    encodeurl = urllib.parse.quote(base_url)

    dingtalkurl = "dingtalk://dingtalkclient/action/openapp?corpid=ding5b2aa85601c5363fffe93478753d9884&container_type=work_platform&app_id=0_1784691312&redirect_type=jump&redirect_url=" + encodeurl
    normalurl = "dingtalk://dingtalkclient/page/link?url=" + encodeurl + "&pc_slide=true"

    msg = {
        "msgtype": "text",
        "text": {
            "content": "【" + stime + "到" + etime + "】的考勤数据已同步完成"
        }
    }
    a = client.message.asyncsend_v2(msg_body=msg, agent_id=AgentId, userid_list=dingtalkuserid.split("。"))

    return json.dumps("推送成功", indent=4, sort_keys=True,
                      default=str,
                      ensure_ascii=False)
